package com.xiaobaibai.controller;

import com.xiaobaibai.bo.ShoppingCarRedisBo;
import com.xiaobaibai.bo.ShoppingCartVo;
import com.xiaobaibai.common.UserCommon;
import com.xiaobaibai.entity.Product;
import com.xiaobaibai.response.ResponseFormat;
import com.xiaobaibai.service.IProductService;
import com.xiaobaibai.service.IShoppingCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = "购物车数据接口")
@RequestMapping("/shopping-cart")
@CrossOrigin
public class ShoppingCartController {

    @Autowired
    private IShoppingCartService shoppingCartService;

    @GetMapping("/list")
    @ApiOperation("根据userId获取购物车信息")
    public ResponseFormat getShoppingCartByUserId(){
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        Integer userId= (Integer) authentication.getPrincipal();
        List<ShoppingCartVo> result = shoppingCartService.getShoppingCartByUserId(userId);
        if(result==null)
            return ResponseFormat.ok("购物车为空");
        return ResponseFormat.ok("购物车信息获取成功",result);
    }

    @PostMapping("/update")
    @ApiOperation("购物车信息发生改变(在页面卸载或者隐藏时再触发)")
    public ResponseFormat addShoppingCart(@RequestBody List<ShoppingCarRedisBo> list){
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        Integer userId= (Integer) authentication.getPrincipal();
        shoppingCartService.addShoppingCart(list,userId);
        return ResponseFormat.ok("购物车更新成功");
    }

}
